package ${baseInfo.basePackage}.${baseInfo.moduleName}.controller;

import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import java.io.PrintWriter;
import net.sf.json.JSONObject;
import java.nio.charset.StandardCharsets;
import ${baseInfo.basePackage}.${baseInfo.moduleName}.model.${baseInfo.classForClassName};
import ${baseInfo.basePackage}.${baseInfo.moduleName}.service.${baseInfo.classForClassName}Service;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.poi.excel.editor.IFontEditor;
import com.ccp.dev.core.poi.excel.style.Color;
import com.ccp.dev.core.poi.excel.style.DataFormat;
import com.ccp.dev.core.poi.excel.style.font.BoldWeight;
import com.ccp.dev.core.poi.excel.style.font.Font;
import com.ccp.dev.core.poi.excel.util.ExcelUtil;
import java.util.ArrayList;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.util.BaseUtil;
<#if selectFlow?? && selectFlow != "">
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
</#if>

/**
 * ${baseInfo.tableComment} 信息操作处理控制器
 * 
 * @author ${baseInfo.author}
 * @date ${baseInfo.datetime}
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "${baseInfo.tableComment}")
@RequestMapping("/${baseInfo.moduleName}/${baseInfo.classForPrefix}")
public class ${baseInfo.classForClassName}Controller extends SysBaseController{
    @Resource
    private ${baseInfo.classForClassName}Service ${baseInfo.classForPrefix}Service;
    @Resource
    private WCustomColumnsService wCustomColumnsService;
<#if selectFlow?? && selectFlow != "">
    @Resource
    private ProcessRunService processRunService;
</#if>

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: ${baseInfo.author}
     * @date: ${baseInfo.datetime}
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到${baseInfo.tableComment}首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        wCustomColumnsService.addCustomCols(request);
        // 当前系统等级
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        modelMap.put("currentSystemLevel", currentSystemLevel);
        // 当前登录用户id
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        <#if baseInfo.showFull?? && baseInfo.showFull>
        return "/iframe/link/${baseInfo.classForPrefix}List";
        <#else>
        return "${baseInfo.classForPrefix}/list";
        </#if>
    }
    <#if baseInfo.showFull?? && baseInfo.showFull>
    /**
    * 功能描述: 跳转页面
    *
    * @return: java.lang.String
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/lists")
    @Action(description="跳转页面", exectype = "页面跳转日志")
    public String viewLists() {
        return "${baseInfo.classForPrefix}/list";
    }
    </#if>

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询${baseInfo.tableComment}",detail="查询数据信息<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else></<#noparse>#</#noparse>if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 添加通用查询条件
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<${baseInfo.classForClassName}> pageDatas = ${baseInfo.classForPrefix}Service.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEdit(pageDatas, false);
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: ${baseInfo.author}
     * @date: ${baseInfo.datetime}
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到${baseInfo.tableComment}新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String ${baseInfo.primaryKey.attrNameForProperty} = RequestUtil.getString(request,"${baseInfo.primaryKey.attrNameForProperty}");
        modelMap.put("${baseInfo.primaryKey.attrNameForProperty}",${baseInfo.primaryKey.attrNameForProperty});
        <#if selectFlow?? && selectFlow != "">
        String runId = RequestUtil.getString(request,"runId");
        modelMap.put("runId",runId);
        </#if>
        return "${baseInfo.classForPrefix}/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: ${baseInfo.classForPrefix} 保存的对象
    * @return: java.lang.Object
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存${baseInfo.tableComment}数据",detail="<<#noparse>#</#noparse>if isAdd>新增<<#noparse>#</#noparse>else>编辑</<#noparse>#</#noparse>if>${baseInfo.tableComment}数据<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else>失败</<#noparse>#</#noparse>if><<#noparse>#</#noparse>if StringUtil.isNotEmpty(modifyInfo)>成功>${modifyInfo}</<#noparse>#</#noparse>if>")
    public Object save(@RequestBody ${baseInfo.classForClassName} ${baseInfo.classForPrefix}) {
        ${baseInfo.primaryKey.attrType} id = ${baseInfo.classForPrefix}.get${baseInfo.primaryKey.attrNameForMethod}();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机${baseInfo.primaryKey.attrNameForMethod}
            <#if baseInfo.primaryKey.attrType == "String">
            ${baseInfo.classForPrefix}.set${baseInfo.primaryKey.attrNameForMethod}(ProjectUUIDUtils.getUUIDFor32());
            <#elseif baseInfo.primaryKey.attrType == "Long">
            ${baseInfo.classForPrefix}.set${baseInfo.primaryKey.attrNameForMethod}(UUIDUtils.getLongId());
            </#if>
            ZhiLiangConst.addCommonFields(${baseInfo.classForPrefix});
            //上报状态
            BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
            if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)) {
                ${baseInfo.classForPrefix}.setReportStatus(ZhiLiangConst.HOSPITAL_INTERNALAPPROVAL_THEAPPROVALISPENDING);
            } else if (BaseUtil.SystemLevel.PLANTLEVEL.equals(currentSystemLevel)) {
                ${baseInfo.classForPrefix}.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            }
            result = ${baseInfo.classForPrefix}Service.add(${baseInfo.classForPrefix});
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            //修改操作
            ZhiLiangConst.updateCommonFields(${baseInfo.classForPrefix});
            result = ${baseInfo.classForPrefix}Service.update(${baseInfo.classForPrefix});
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(${baseInfo.classForPrefix}Service.getOneById(id), ${baseInfo.classForPrefix}));
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到${baseInfo.tableComment}详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String ${baseInfo.primaryKey.attrNameForProperty} = RequestUtil.getString(request,"${baseInfo.primaryKey.attrNameForProperty}");
        modelMap.put("${baseInfo.primaryKey.attrNameForProperty}",${baseInfo.primaryKey.attrNameForProperty});
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        return "${baseInfo.classForPrefix}/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"${baseInfo.primaryKey.attrNameForProperty}"
    * @return: java.lang.Object
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询${baseInfo.tableComment}的一条数据",detail="根据主键id查询${baseInfo.tableComment}的数据<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else>失败</<#noparse>#</#noparse>if>")
    public Object get(@RequestParam("id") String ${baseInfo.primaryKey.attrNameForProperty}) {
        <#if baseInfo.primaryKey.attrType == "Long">
        Long ${baseInfo.primaryKey.attrNameForProperty}ToLong = Long.parseLong(${baseInfo.primaryKey.attrNameForProperty});
        ${baseInfo.classForClassName} ${baseInfo.classForPrefix} = ${baseInfo.classForPrefix}Service.getOneById(${baseInfo.primaryKey.attrNameForProperty}ToLong);
        <#elseif baseInfo.primaryKey.attrType == "String">
        ${baseInfo.classForClassName} ${baseInfo.classForPrefix} = ${baseInfo.classForPrefix}Service.getOneById(${baseInfo.primaryKey.attrNameForProperty});
        </#if>
        if (null == ${baseInfo.classForPrefix}) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",${baseInfo.classForPrefix});
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"${baseInfo.primaryKey.attrNameForProperty}"
    * @return: java.lang.Object
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除${baseInfo.tableComment}数据",exectype = "删除日志",detail="删除数据信息<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else>失败</<#noparse>#</#noparse>if>")
    public Object delete(@RequestParam("id") String ${baseInfo.primaryKey.attrNameForProperty}) {
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            ${baseInfo.classForClassName} ${baseInfo.classForPrefix} = ${baseInfo.classForPrefix}Service.getOneById(key);
            if (!userId.equals(${baseInfo.classForPrefix}.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
            if (Objects.nonNull(${baseInfo.classForPrefix}.getReportStatus()) && !ZhiLiangConst.NOESCALATIONREQUIRED.equals(${baseInfo.classForPrefix}.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(${baseInfo.classForPrefix}.getReportStatus()) && !ZhiLiangConst.HOSPITAL_INTERNALAPPROVAL_THEAPPROVALISPENDING.equals(${baseInfo.classForPrefix}.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待上报、无需上报和院内待审批的数据");
            }
        }
        if (StringUtil.isEmpty(${baseInfo.primaryKey.attrNameForProperty})) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        int result = ${baseInfo.classForPrefix}Service.delByIdArray(${baseInfo.primaryKey.attrNameForProperty}.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到${baseInfo.tableComment}导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "${baseInfo.classForPrefix}/import";
    }

    /**
    * 功能描述: 跳转到导出选择字段页面
    *
    * @param: [request] http请求
    * @param: modelMap
    * @return: java.lang.String
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    * @throws Exception
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到${baseInfo.tableComment}导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(${baseInfo.classForClassName}.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
    * 功能描述: 导出${baseInfo.tableComment}数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping("/exportData")
    @Action(description="导出${baseInfo.tableComment}数据信息",detail="导出${baseInfo.tableComment}数据信息<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else></<#noparse>#</#noparse>if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        List<${baseInfo.classForClassName}> list = this.${baseInfo.classForPrefix}Service.queryAll(queryFilter);
        if (list.isEmpty()) {
            list.add(new ${baseInfo.classForClassName}());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, list, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    @ResponseBody
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        Map<String, Object> map = new AbstractImpUtil(){
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;
                return returnType;
            }
        }.reverseModels(excelEntity, ${baseInfo.classForClassName}.class);
        String msg = map.get("msg").toString();
        List<${baseInfo.classForClassName}> list = (List<${baseInfo.classForClassName}>) map.get("instList");
        if (StringUtil.isEmpty(msg)) {
            this.${baseInfo.classForPrefix}Service.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("dataSource.importXml.success");
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail(msg);
        }
    }

    <#if selectFlow?? && selectFlow != "">
    /**
     * 功能描述: 跳转至modify页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/modify")
    @Action(description="跳转到${baseInfo.tableComment}modify页面")
    public String viewModify(HttpServletRequest request,ModelMap modelMap) {
        String ${baseInfo.primaryKey.attrNameForProperty} = RequestUtil.getString(request,"${baseInfo.primaryKey.attrNameForProperty}");
        modelMap.put("${baseInfo.primaryKey.attrNameForProperty}",${baseInfo.primaryKey.attrNameForProperty});
        return "${baseInfo.classForPrefix}/modify";
    }

    /**
     * 功能描述: 跳转至detail页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/detail")
    @Action(description="跳转到${baseInfo.tableComment}detail页面")
    public String viewDetail(HttpServletRequest request,ModelMap modelMap) {
        String ${baseInfo.primaryKey.attrNameForProperty} = RequestUtil.getString(request,"${baseInfo.primaryKey.attrNameForProperty}");
        modelMap.put("${baseInfo.primaryKey.attrNameForProperty}",${baseInfo.primaryKey.attrNameForProperty});
        return "${baseInfo.classForPrefix}/detail";
    }

    /**
    * 功能描述: 启动流程
    */
    @PostMapping("/run")
    @ResponseBody
    @Action(description="启动${baseInfo.tableComment}流程",detail="启动流程<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else></<#noparse>#</#noparse>if>")
    public Object run(HttpServletRequest request,@RequestBody ${baseInfo.classForClassName} ${baseInfo.classForPrefix}){
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        //实体主键
        String ${baseInfo.primaryKey.attrNameForProperty} = ${baseInfo.classForPrefix}.get${baseInfo.primaryKey.attrNameForMethod}();
        int isList = RequestUtil.getInt(request,"isList",1);
        ProcessCmd  processCmd = new ProcessCmd();
        //流程Key
        processCmd.setModelKey("${selectFlow}");
        processCmd.setUserAccount(sysUser.getAccount());
        try {
            if(StringUtil.isNotEmpty(${baseInfo.primaryKey.attrNameForProperty})){
                if(isList == 1){
                    ${baseInfo.classForPrefix} = ${baseInfo.classForPrefix}Service.getOneById(${baseInfo.primaryKey.attrNameForProperty});
                }
                processCmd.setBusinessKey(${baseInfo.primaryKey.attrNameForProperty});
                processRunService.startProcess(processCmd);
                <#list baseInfo.columns as column>
                <#if column.columnName == "updateBy">
                ${baseInfo.classForPrefix}.setUpdateBy(ContextUtil.getCurrentUserId());
                </#if>
                <#if column.columnName == "updateTime">
                ${baseInfo.classForPrefix}.setUpdateTime(new Date());
                </#if>
                </#list>
                ${baseInfo.classForPrefix}Service.update(${baseInfo.classForPrefix});
            }else{
                String genId = UUIDUtils.getUUIDFor32();
                processCmd.setBusinessKey(genId);
                ${baseInfo.classForPrefix}.set${baseInfo.primaryKey.attrNameForMethod}(genId);
                String tenantId = ContextUtil.getCurrentUserTenantId();
                processRunService.startProcess(processCmd);
                <#list baseInfo.columns as column>
                <#if column.columnName == "tenantId">
                ${baseInfo.classForPrefix}.setTenantId(ContextUtil.getCurrentUserTenantId());
                </#if>
                <#if column.columnName == "createBy">
                ${baseInfo.classForPrefix}.setCreateBy(ContextUtil.getCurrentUserId());
                </#if>
                <#if column.columnName == "createTime">
                ${baseInfo.classForPrefix}.setCreateTime(new Date());
                </#if>
                </#list>
                ${baseInfo.classForPrefix}Service.add(${baseInfo.classForPrefix});
            }
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("flow.start.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("flow.start.failure");
        }
    }
    </#if>

    /**
    * 查询上报的信息
    *
    * @param id        业务数据主键
    * @param tableName 业务表名
    * @return
    */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(@RequestParam("id") String id, @RequestParam("tableName") String tableName) throws IllegalAccessException {
        //业务数据
        List<${baseInfo.classForClassName}> reportList = ${baseInfo.classForPrefix}Service.reportList(id, tableName);
        ZhiLiangConst.showName(reportList);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }

}
